package cn.virens.web.controller.api;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.MediaType;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.virens.util.RequestUtil;
import cn.virens.web.common.BaseJSONController;

@RestController
@RequestMapping("/api/upload")
public class FileUploadContorller extends BaseJSONController {
	private final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 文件不存在
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST)
	public Model uploadPOST(HttpServletRequest request, HttpServletResponse response, Model model) {
		return renderFail(model, "文件不存在");
	}

	/**
	 * 文件上传
	 * @param file
	 * @param request
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(name = "{path}.json", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
	public Model upload(@PathVariable(name = "path", required = true) String path, @RequestParam("file") MultipartFile file, HttpServletRequest request, Model model) throws IOException {
		if (file == null) return renderFail(model, "文件不存在");
		// 获取存储目录
		String rootPath = request.getServletContext().getRealPath("/");
		String realPath = "/upload/" + path + "/" + df.format(new Date()) + "/";
		File savePath = new File(rootPath, realPath);
		if (!savePath.exists()) savePath.mkdirs();

		// 创建文件名
		String fileName = file.getOriginalFilename();
		String fileSuffix = fileName.substring(fileName.lastIndexOf("."));
		String fileNameMd5 = RequestUtil.getValueStr(request, "md5", DigestUtils.md2Hex(fileName));
		// 移动文件到上传目录
		file.transferTo(new File(savePath, fileNameMd5 + fileSuffix));
		// 返回文件信息
		model.addAttribute("size", file.getSize());
		model.addAttribute("ContentType", file.getContentType());
		model.addAttribute("name", fileName);

		logger.debug("文件上传成功(size:{}/type:{}):{}", file.getSize(), file.getContentType(), fileName);

		return renderSuccess((realPath + fileNameMd5 + fileSuffix), model);
	}
}
